import api from '@/utils/api'
import { ElMessage, ElMessageBox } from 'element-plus'
export function localGet(key) {
  const value = window.localStorage.getItem(key)
  try {
    return JSON.parse(window.localStorage.getItem(key))
  } catch (error) {
    return value
  }
}

export function localSet(key, value) {
  window.localStorage.setItem(key, JSON.stringify(value))
}

export function localRemove(key) {
  window.localStorage.removeItem(key)
}

// 判断内容是否含有表情字符，现有数据库不支持。
export function hasEmoji(str = '') {
  const reg =
    /[^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n]/g
  return str.match(reg) && str.match(reg).length
}

export function indexMethod(idx, pageNum = 1, pageSize = 5) {
  idx++
  return `${(pageNum - 1) * pageSize + idx}`
}

export async function toolGetList(state, apiList, paramFilters) {
  if (document.querySelector('#listTop')) {
    document.querySelector('#listTop').scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'start' })
  }
  const params = {
    page: state.page,
    rows: state.pageSize,
    order: state.order,
    sortby: state.sortby
  }
  Object.assign(params, paramFilters)
  try {
    state.listLoading = true
    const res = await api.http.get(api.ajaxUrl + apiList + '?' + api.stringify(params))
    state.items = res.items
    state.total = res.total
    state.listLoading = false
    return res
  } catch (error) {
    console.log(error)
    state.listLoading = false
    return null
  }
}

export async function toolGetMenus(state, apiDb) {
  try {
    state.listLoading = true
    const res = await api.http.get(api.ajaxUrl + apiDb + '/menus')
    Object.keys(state.menus).forEach(function(key) {
      if (Object.prototype.hasOwnProperty.call(res, key)) {
        state.menus[key] = res[key]
      }
    })
    return res
  } catch (error) {
    console.log(error)
    return null
  }
}

export const toolDbSubmit = async function(dbForm, id, state, apiDb, funcSuccess) {
  const valid = await dbForm.value.validate()
  if (valid) {
    const confirm = await ElMessageBox.confirm('您确认吗？', '提示', {})
    if (confirm === 'confirm') {
      state.dbLoading = true
      const params = Object.assign({}, state.dbForm)
      try {
        let res = null
        if (state.dbMethod === 'create') {
          res = await api.http.post(api.ajaxUrl + apiDb, params)
        } else if (state.dbMethod === 'update') {
          res = await api.http.put(api.ajaxUrl + apiDb + '/' + id, params)
        }
        if (res.code !== 0) {
          ElMessage({
            message: res.msg,
            type: 'error'
          })
          state.dbLoading = false
        } else {
          funcSuccess(state, apiDb)
        }
      } catch (error) {
        state.dbLoading = false
      }
    }
  }
}

export const toolDbSuccess = async function(state, apiDb) {
  state.dbLoading = false
  ElMessage({
    message: '修改成功',
    type: 'success'
  })
  state.dbFormVisible = false
  await toolGetList(state, apiDb, state.filters)
}

export const toolDelete = async function(state, apiDb, id) {
  const confirm = await ElMessageBox.confirm('您确认吗？', '提示', {})
  if (confirm === 'confirm') {
    try {
      const res = await api.http.delete(api.ajaxUrl + apiDb + '/' + id)
      if (res.code === 0) {
        ElMessage.success('已删除')
        state.page = 1
        toolGetList(state, apiDb, state.filters)
      }
    } catch (error) {
      console.log(error)
    }
  }
}

export const toolOrderChange = async function(state, apiDb, column) {
  state.order = column.order === 'ascending' ? 'asc' : 'desc'
  state.sortby = column.prop
  state.page = 1
  await toolGetList(state, apiDb, state.filters)
}

export const statusMap = {
  1: 'success',
  0: 'info'
}

export const pathMap = {
  login: '登录',
  dashboard: '仪表盘',
  user: '用户管理',
  role: '角色管理',
  shop: '店铺管理',
  item: '商品管理',
  order: '订单管理'
}
